package de.logicline.cvss.ui.view.table;

import java.util.Date;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;

import de.logicline.cvss.vo.CVSSearchEntry;

public class TableFilter extends ViewerFilter {
	//private ChangeLogView view;
	public String author;
	public Date fromDate;
	public Date toDate;
	public String comment;
	public boolean isOr;
	public TableFilter( String author, String comment,
			Date fromDate, Date toDate, boolean isOr) {
		//this.view = hView;
		this.author = author;
		this.comment = comment;
		this.fromDate = fromDate;
		this.toDate = toDate;
		this.isOr = isOr;
	}
	/**
	 * @see ViewerFilter#select(Viewer, Object, Object)
	 */
	public boolean select(Viewer aviewer, Object parentElement, Object element) {
		if (element instanceof CVSSearchEntry) {
			CVSSearchEntry entry = (CVSSearchEntry) element;
			if (isOr) {
				//empty fields should be considered a non-match
				return (hasAuthor() && authorMatch(entry))
						|| (hasDate() && dateMatch(entry))
						|| (hasComment() && commentMatch(entry));
			} else {
				//"and" search
				//empty fields should be considered a match
				return (!hasAuthor() || authorMatch(entry))
						&& (!hasDate() || dateMatch(entry))
						&& (!hasComment() || commentMatch(entry));
			}
		}
		return false;
	}
	protected boolean authorMatch(CVSSearchEntry entry) {
		return entry.getAuthor().equals(author);
	}
	protected boolean commentMatch(CVSSearchEntry entry) {
		return !(entry.getComment().toLowerCase()
				.indexOf(comment.toLowerCase()) == -1);
	}
	protected boolean dateMatch(CVSSearchEntry entry) {
		return (fromDate.before(entry.getDate()))
				&& (toDate.after(entry.getDate()));
	}
	protected boolean hasAuthor() {
		return !author.equals("");
	}
	protected boolean hasComment() {
		return !comment.equals("");
	}
	protected boolean hasDate() {
		return fromDate != null && toDate != null;
	}
}